#include "pintaros.h"
#include "command.h"
#include "response.h"

void CommandInterpreter(struct buffer_struct *rx_buffer, struct apdu_res_struct *apdu_res)
{

  /**
   * @brief interpret the received TPDU into APDU
   */
  apdu_res->CLA = rx_buffer->buffer[0];
  apdu_res->INS = rx_buffer->buffer[1];
  apdu_res->P1  = rx_buffer->buffer[2];
  apdu_res->P2  = rx_buffer->buffer[3];
  apdu_res->P3  = rx_buffer->buffer[4];

  /**
   * @brief check CLA
   */
  if(apdu_res->CLA == 60) {

    /**
     * @brief search Instruction map for the received APDU INS to call approriate command handler
     */
    if(cmdSearchINS(apdu_res->INS, cmdHandler)) {
      cmdHandler(apdu_res);
    }
    /**
     * @brief if instruction not found, set response type to CLA Not Supported
     */
    else {
      apdu_res->rspn_type = INSNotSupported;
    }
  } 
  else {
    apdu_res->rspn = CLANotSupported;
  }

}

int cmdSearchINS(uint8_t INS, int *cmdHandler(int))
{
  for(i = 0; i < MAX_INS; i++) {
    if(cmd_maps[i].inst == INS) {
      cmdHandler = cmd_maps[i].handler;
      return 0;
    }
  }

  return -1;
}

int cmd_SELECT(struct apdu_res_struct * apdu_res)
{

}
